<template>
  <div>
    <el-drawer
      class="dia-style"
      :title="title"
      :visible.sync="open"
      :size="950"
      :close-on-click-modal="false"
      :wrapper-closable="false"
      @close="cancel"
    >
      <div class="drawer-container">
        <hk-form
          ref="formRef"
          class="hk-flex"
          :data="formData"
          :rules="rules"
          :label-width="labelWidth"
          :btn-hidden="btnHidden"
          :dict-list="dictList"
          :form-labels="formLabels"
          :disabled="title=='详情'"
        >
          <template #filter-applicantName>
            <el-button
              icon="el-icon-thumb"
              style="margin-right: 1.25rem"
              @click="handleSelectData"
            >请选择</el-button>
            <span v-if="!importProduct.length &&$route.query.showDetail">暂无数据</span>
            <hk-table
              v-if="importProduct.length"
              :table-data="importProduct"
              :table-columns="importTableList"
              :show-index="true"
              :total="total"
              :show-pag="false"
              :table-height="80"
              :query-params="queryParams"
              @changePage="getDataList"
            />
          </template>
          <template #filter-evidenceFileList>
            <div class="hk-flex-column">
              <hk-table
                :table-data="tableData"
                :table-columns="tableDataList"
                :show-pag="false"
                :loading="loading"
                show-index
                :rules="rules"
                is-need-index
                :dict-list="dictList"
                operate
              >
                <template #cght="scope">
                  <span v-if="scope.row.row.fileUrl">
                    <!-- {{ scope.row.row.fileUrl }} / -->
                    {{ scope.row.row.fileName }}
                  </span>
                  <span v-else>
                    <el-button type="text" style="display:block" @click="uploadFiles(scope.row.$index)">上传文件</el-button>
                    <span>支持扩展名：.pdf</span>
                  </span>
                </template>
                <template #operate="scope">
                  <el-button type="text" @click="handleDelete(scope.row.index)">删除</el-button>
                </template>
              </hk-table>
              <el-button icon="el-icon-plus" class="add-row" @click="addRow">增加行</el-button>
            </div>
          </template>
        </hk-form>

        <SelectDialog
          ref="selectRef"
          :table-columns="importTableList"
          :page-function="productList"
          title="选择申请运维人员"
          :check-data="importProduct"
          :radiobox="true"
          @handleSubmit="dialogSubmitEvent"
        />
      </div>
      <div class="drawer-footer">
        <el-button v-if="title=='新增'|| title=='编辑'" type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <hk-upload ref="import_dia" :url="url" title="上传" :accept="accept" success-desc="上传成功！" @submit="currentUploadInfo" />
  </div>
</template>

<script>
import { parseTime } from '@/utils/hongke'
import HkForm from '@/components/Hk-Form'
import HkTable from '@/components/Hk-Table/index.vue'
// import { productList } from '@/api/milkyway/gatherData'
import { details, update, add, productList, getDict } from '@/api/specialProject/exit'
import SelectDialog from '@/components/SelectDialog/index.vue'
export default {
  components: { HkForm, HkTable, SelectDialog },
  props: {
    title: {
      type: String,
      default: '新增'
    }
  },
  data() {
    return {
      queryParams: {
        current: 1,
        size: 10
      },
      // 是否显示弹出层
      open: false,
      // 标题宽度
      labelWidth: '110',
      // 是否显示按钮
      btnHidden: true,
      formData: {},
      total: 0,
      loading: false,
      importProduct: [],
      url: window.baseUrl.action + '/attachment/upload',
      accept: '.pdf',
      importTableList: [
        { label: '人员名称', param: 'userName' },
        { label: '涉密等级', param: 'secLevel' },
        { label: '运维岗位', param: 'unitName' }
      ],
      tableData: [{
        fileUrl: '',
        fileName: '',
        materialName: '',
        illustrate: '',
        notes: '' }],
      // 相关材料 上传操作对应table下标
      fileTableIndex: 0,
      tableDataList: [
        { label: '材料名称', param: 'materialName', type: 'input', maxlength: 20 },
        { label: '说明', param: 'illustrate', type: 'input', maxlength: 50 },
        { label: '证明材料', param: 'cght', type: 'slot', width: 200 },
        { label: '备注', param: 'notes', type: 'input', maxlength: 50 }
      ],
      dictList: {
        'channelList': [],
        'eventList': [],
        'statusList': [],
        'sourcePlatformList': [],
        'secLevelList': []
      },

      formLabels: [
        {
          label: '申请运维人员',
          field: 'applicantName',
          type: 'slot',
          span: 24
        },
        {
          label: '出境时间段',
          field: 'time',
          type: 'datetimerange',
          span: 24
        },
        {
          label: '目的地',
          field: 'destination',
          type: 'input',
          maxlength: 50,
          span: 24
        },
        {
          label: '申请理由',
          field: 'reason',
          type: 'textarea',
          hidden: false,
          attrs: {
            rows: '3'
          },
          maxlength: 200,
          span: 24
        },
        {
          label: '相关材料',
          field: 'evidenceFileList',
          type: 'slot',
          span: 24
        },
        {
          label: '审批意见',
          field: 'opinions',
          type: 'select',
          list: 'secLevelList'
        }
      ],
      // 表单校验
      rules: {
        applicantName: [{ required: true, message: '申请运维人员不能为空', trigger: 'change' }],
        evidenceFileList: [{ required: true, message: '相关材料不能为空', trigger: 'change' }],
        destination: [{ required: true, message: '目的地不能为空', trigger: 'blur' }],
        time: [{ required: true, message: '出境时间段不能为空', trigger: 'blur' }],
        opinions: [{ required: true, message: '审批意见不能为空', trigger: 'blur' }]
      },
      applicantId: '' // 申请人id
    }
  },
  watch: {
    title() {
      if (this.title === '详情') {
        this.tableDataList = [
          { label: '材料名称', param: 'materialName', type: 'input', maxlength: 20 },
          { label: '说明', param: 'illustrate', type: 'input', maxlength: 50 },
          { label: '证明材料', param: 'cght', type: 'slot', width: 200 },
          { label: '备注', param: 'notes', type: 'input', maxlength: 50 }
        ]
      } else {
        this.tableDataList = [
          { label: '材料名称', param: 'materialName', type: 'input', maxlength: 20 },
          { label: '说明', param: 'illustrate', type: 'input', maxlength: 50 },
          { label: '证明材料', param: 'cght', type: 'slot', width: 200 },
          { label: '备注', param: 'notes', type: 'input', maxlength: 50 }
        ]
      }
    }
  },
  mounted() {
    this.getDictDatas()
  },
  methods: {
    show(data) {
      this.open = true
      if (typeof data === 'object') {
        details({ id: data.id }).then(res => {
          this.formData = {
            id: res.id,
            applicantName: res.applicantName,
            destination: res.destination,
            reason: res.reason,
            evidenceFileList: res.evidenceFileList,
            opinions: res.opinions,
            time: [res.startTime, res.endTime]
          }
          this.applicantId = res.applicantId
          // 表格编辑赋值
          this.tableData = this.formData.evidenceFileList
          this.importProduct = [{
            userName: res.applicantName,
            secLevel: res.applicantLevel,
            unitName: res.applicantPost
          }
          ]
        })
      }
    },
    // 字典获取
    getDictDatas() {
      getDict({ code: 'approvalOpinions' }).then((res) => {
        this.dictList.secLevelList = res.map((o) => {
          o.label = o.dictValue
          o.value = o.dictKey
          return o
        })
      })
    },
    // 获取运维人员
    productList(queryParams) {
      return productList(queryParams)
    },
    // 上传文件
    uploadFiles(index) {
      this.fileTableIndex = index
      this.$refs.import_dia.show()
    },
    getDataList(val) {
      this.queryParams = { ...this.queryParams, ...val }
    },
    handleSelectData() {
      this.$refs.selectRef.show(this.importProduct)
    },
    dialogSubmitEvent(data) {
      this.$set(this.formData, 'applicantName', data[0].userName)
      this.importProduct = data
    },
    addRow() {
      this.tableData.push({
        fileUrl: '',
        fileName: '',
        materialName: '',
        illustrate: '',
        notes: '' })
    },
    handleDelete(idx) {
      this.tableData.splice(idx, 1)
    },
    submitForm() {
      // 遍历数组对象每项是否都为空
      const evidenceFileList = []
      console.log(this.tableData)
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i]
        if (JSON.stringify(item) === '{}') {
          continue
        }
        let itemEmpty = false
        for (const key in item) {
          if (!item[key]) {
            itemEmpty = true
          }
        }
        if (!itemEmpty) {
          evidenceFileList.push(item)
        }
      }
      this.$set(this.formData, 'evidenceFileList', evidenceFileList)
      this.$refs.formRef.handleFormSubmit('formLabels').then(res => {
        const startTime = parseTime(res.time[0])
        const endTime = parseTime(res.time[1])
        // const opinions = res.opinions === '同意' ? 1 : 2
        if (this.formData.id) {
          update({ ...res, applicantId: this.applicantId, startTime, endTime, evidenceFileList: evidenceFileList }).then((response) => {
            this.$modal.msgSuccess('更新成功')
            this.$emit('handleSubmit')
            this.cancel()
          }).catch(err => {
            this.$message.error(err.message)
          })
        } else {
          add({ ...res, applicantId: this.importProduct[0].id, applicantName: this.importProduct[0].userName,
            applicantLevel: this.importProduct[0].secLevel, applicantPost: this.importProduct[0].unitName,
            startTime, endTime, evidenceFileList: this.tableData }).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.$emit('handleSubmit')
            this.cancel()
          }).catch(err => {
            this.$message.error(err.message)
          })
        }
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.$refs.formRef.resetForm('formLabels')
      this.tableData = [{
        fileUrl: '',
        fileName: '',
        materialName: '',
        illustrate: '',
        notes: ''
      }]
      this.formData = {}
      this.importProduct = []
    },
    // 接收上传文件信息
    currentUploadInfo(data) {
      this.$set(this.tableData[this.fileTableIndex], 'fileUrl', data.fileUrl)
      this.$set(this.tableData[this.fileTableIndex], 'fileName', data.fileName)
    }
  }
}
</script>
    <style lang="scss" scoped>
    .dark-theme{
      span{
        color: #fff !important;
      }
    }
    .sub-title {
      height: 1.25rem;
      border-left: .125rem solid #4B6EEF;
      margin-bottom: 1.375rem;

      span {
        margin-left: .5rem;

      }
    }

    .ml10 {
      margin-left: .625rem;
    }

    .mt40 {
      margin-top: 2.5rem;
    }
    .hk-flex-column{
      margin-top: 20px;
      margin-left: -110px;
    }
  .drawer-container{
      padding: 0;
  }
  .add-row{
    margin-top: 20px;
  }
  ::v-deep{

  }
    </style>

